#!/usr/bin/env python
# -*- coding: utf-8 -*-

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch

from BeautifulSoup import BeautifulSoup
import urllib
import re

from google.appengine.api.urlfetch import DownloadError
from HTMLParser import HTMLParseError


def getMobileUrlsFromTistory(url):
    result = urlfetch.fetch( url )
    
    mobileUrls = []
    title = ''
    if result.status_code == 200:
        soup = BeautifulSoup( result.content )
        items = soup.findAll(name='span', attrs={'class': 'trackback-url'})
        
        for item in items:
            mobileUrl = item.string.replace('trackback', 'm')
            mobileUrls.append(mobileUrl)
            
        title = soup.title.string
                    
    return mobileUrls, title
                
def getMp3LinksFromMobileUrls(mobileUrls):
    mp3Links = []
    
    for url in mobileUrls:
        result = urlfetch.fetch( url )
        if result.status_code == 200:
            soup = BeautifulSoup( result.content )
            links = soup.findAll( name='a', attrs={'href': re.compile('http://.{1,9}\.tistory\.com/upload_control/download\.blog\?[^>]+', re.UNICODE)} )
            for link in links:
                mp3LinkUrl = link['href'] + '&filename=' + urllib.quote( link.string.encode('cp949') )
                mp3Links.append( {'url': mp3LinkUrl, 'url_linktext': link.string} )
            
    return mp3Links
        
class GetMp3LinksPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
        
        urls = []
        
        url = self.request.get('url').encode('utf-8')
        if url != '':
            try:
                url, query = urllib.splitquery(url)
                if query != None:
                    url = url + urllib.quote( query )
                mobileUrl, title = getMobileUrlsFromTistory( url )
                mp3Links = getMp3LinksFromMobileUrls( mobileUrl )
                urls += mp3Links
            except HTMLParseError:            
                pass
            except DownloadError:
                pass
            except:
                pass
        
        template_values = {
                           'title': title,
                           'urls': urls,
                          }
        
        import os
        path = os.path.join(os.path.dirname(__file__), 'html/GetMp3LinksPage.html')
        self.response.out.write(template.render(path, template_values))
        
#EOF